package com.tim.framework.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;

import com.tim.framework.common.PageList;
import com.tim.framework.common.PageProperty;
import com.tim.framework.dao.EntityDao;
import com.tim.framework.service.BaseService;

public class SpringBaseServiceImpl<T> implements BaseService<T> {
	private EntityDao<T> baseDao;

	public EntityDao<T> getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(EntityDao<T> _baseDao) {
		baseDao = _baseDao;
	}

	@SuppressWarnings("unchecked")
	public T getModel(Serializable id) {
		T po = baseDao.getById(id);
		return (T) po;
	}

	@SuppressWarnings("unchecked")
	public Serializable create(T model) throws DataAccessException {
		return baseDao.create(model);
	}

	@SuppressWarnings("unchecked")
	public void update(T model) throws DataAccessException {
		baseDao.update(model);

	}

	@SuppressWarnings("unchecked")
	public void delete(T model) throws DataAccessException {
		baseDao.delete(model);
	}

	@SuppressWarnings("unchecked")
	public int getAllCount() throws DataAccessException {
		return baseDao.findAllCount();
	}

	@SuppressWarnings("unchecked")
	public int getCount(PageProperty pp) throws DataAccessException {
		return baseDao.findCount(pp);
	}

	@SuppressWarnings("unchecked")
	public List<T> getList(PageProperty pp) throws DataAccessException {
		return baseDao.findPageList(pp);
	}

	@SuppressWarnings("unchecked")
	public PageList<T> getPageList(PageProperty pp) throws DataAccessException {
		int count = getCount(pp);
		if (count > 0) {
			PageList<T> pageList = new PageList<T>(pp, count, getList(pp));
			return pageList;
		}
		return new PageList<T>(pp, 0, new ArrayList<T>());
	}

	/**
	 * 执行update或delete的hql语句.
	 * 
	 * @param String
	 *            执行语句的模式update或delete
	 * @param String
	 *            update或delete之后的sql语句
	 * @param List
	 *            执行参数
	 * @return Integer 影响的行数.
	 */
	public int executeUpdate(String model, String sql, List<Object> params) {
		return this.baseDao.executeUpdate(model, sql, params);
	}

	/**
	 * 执行hql查询语句.
	 * 
	 * @param sql
	 *            hql语句.
	 * @param params
	 *            参数列表.
	 */
	@SuppressWarnings("unchecked")
	public List<Object> executeHqlQuery(String sql, List<Object> params) {
		return this.baseDao.executeHqlQuery(sql, params);
	}
}
